package main

import (
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"fmt"
	"gorm_demo/model"
)

func main() {

	db, err := gorm.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/test?charset=utf8&parseTime=True&loc=Local")
	db.LogMode(true)
	if err != nil {
		fmt.Println(err.Error())
	}

	//belongsTo(db)

	//hasOne(db)
	//hasMany(db)
	manyToMany(db)
}

//belongs to
func belongsTo(db *gorm.DB) {
	//profile belongs to user
	user := model.User{}
	db.First(&user)
	fmt.Println(user)
	profile := model.Profile{}
	db.Model(user).Related(&profile)
	fmt.Println(user)
	fmt.Println(profile)
}

func hasOne(db *gorm.DB) {
	stu := model.Student{}
	db.First(&stu)
	fmt.Println(stu)
	toy := model.Toy{}
	db.Model(stu).Related(&toy)
	fmt.Println(toy)
}

func hasMany(db *gorm.DB) {
	persion := model.Persion{}
	db.Last(&persion)
	fmt.Println(persion)
	emails := make([]model.Email, 10)
	db.Model(persion).Related(&emails)
	fmt.Println(emails)
}

func manyToMany(db *gorm.DB) {
	animal := model.Animal{}
	db.First(&animal)
	fmt.Println(animal)
	foods := make([]model.Food, 10)
	db.Model(animal).Related(&foods, "foods")
	fmt.Println(foods)


}
